//
//  ActivitySearchViewController.m
//  TheRoadAD
//
//  Created by 宁宁 on 16/8/25.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "ActivitySearchViewController.h"

#import "SearchHistoryTableViewCell.h"//历史记录Cell
#import "SearchScreenTableViewCell.h"//筛选条件Cell

#import "SearchResultsViewController.h"//搜索结果Controller

@interface ActivitySearchViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@end

#define HISTORY @"SearchHistory"

/**活动主页*/
#define Days @[@"1天", @"3天以内", @"3-5天", @"7天", @"10天"]
#define City @[@"杭州", @"杭州以外"]
#define Type @[@"越野", @"赛道日", @"自驾游", @"室内聚会", @"静态展示"]
#define Activity @[@"天数:", @"城市:", @"类型:"]

/**兜一兜*/
#define Time @[@"随时", @"不一定", @"明天", @"最近三天", @"最近五天"]
#define HavingCar @[@"是", @"否"]
#define NumOfPeople @[@"1-4人", @"5-8人", @"9-12人", @"13-16人"]
#define Sex @[@"男", @"女"]
#define Age @[@"20岁以下", @"20-30岁", @"30-40岁", @"40-50岁", @"50-60岁"]
#define Education @[@"高中及以下", @"专科", @"本科及以上"]
#define JTZS @[@"时间:", @"所在地区:", @"是否有车:", @"可带几人:", @"性别:", @"年龄:", @"学历:"]

@implementation ActivitySearchViewController
{
    UIView *_frame;
    UITextField *_searchText;
    
    NSUserDefaults *_defaults;
    /**沙盒历史记录*/
    NSMutableArray *_searchHistoryArray;
    
    
    NSArray *_conditionArray;
    NSArray *_titleArray;
}

 static NSString *const SearchHistoryTableViewCellID = @"SearchHistoryTableViewCell";
 static NSString *const SearchScreenTableViewCellID = @"SearchScreenTableViewCell";

- (void)viewWillDisappear:(BOOL)animated{
    _frame.hidden = YES;
    [_searchText resignFirstResponder];
}
- (void)viewWillAppear:(BOOL)animated{
    _frame.hidden = NO;
    
    if (!_searchHistoryArray) {
        _searchHistoryArray = [NSMutableArray array];
    }else {
        [_searchHistoryArray removeAllObjects];
    }
    
    if ([_defaults objectForKey:HISTORY]) {
        NSArray *arr = [_defaults objectForKey:HISTORY];
        [_searchHistoryArray addObjectsFromArray:arr];
    }
    
    
    if (self.tableView) {
        [self.tableView removeFromSuperview];
    }
    //注册TableView 设置页眉页脚
    [self createTableView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _defaults = [NSUserDefaults standardUserDefaults];
        
    [self createData];
    
    //设置导航栏
    [self setNav];
    
}

- (void)createData{
    if (_index == 0) {
        _conditionArray = @[Days, City, Type];
        _titleArray = Activity;
    }else if (_index == 1){
        
    }else if (_index == 2){
        _conditionArray = @[Time, City, HavingCar, NumOfPeople, Sex, Age, Education];
        _titleArray = JTZS;
    }else if (_index == 3){
        
    }else if (_index == 4){
        
    }else if (_index == 5){
        
    }else ;
}

#pragma mark === 设置导航栏 ===
- (void)setNav{
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_122"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = back;
    
    UIBarButtonItem *search = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searching)];
    
    self.navigationItem.rightBarButtonItem = search;
    
    
    _frame = [[UIView alloc] initWithFrame:CGRectMake(40, 8, Screen_Width - 90, 30)];
    _frame.layer.borderWidth = 1;
    _frame.layer.borderColor = RGBColor(194, 194, 194).CGColor;
    _frame.layer.cornerRadius = 12;
    [self.navigationController.navigationBar addSubview:_frame];
    
    UIImageView *searchImg = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 20, 20)];
    searchImg.image = [UIImage imageNamed:@"find_1"];
    [_frame addSubview:searchImg];
    
    _searchText = [[UITextField alloc] initWithFrame:CGRectMake(searchImg.frame.origin.x + searchImg.frame.size.width + 5, 5, Screen_Width - 90 - (searchImg.frame.origin.x + searchImg.frame.size.width + 5), 20)];
    _searchText.font = [UIFont fontWithName:AppFont size:13];
    _searchText.clearButtonMode = UITextFieldViewModeWhileEditing;
    _searchText.delegate = self;
    [_frame addSubview:_searchText];
}

#pragma mark === 创建TableView 设置页眉页脚 ===
- (void)createTableView{
    
    self.tableView= [[UITableView alloc]initWithFrame:CGRectMake(0,0, Screen_Width, Screen_Height)style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsVerticalScrollIndicator = NO;//去掉滑动竖条
    [self.view addSubview:self.tableView];
    
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 60)];
    UILabel *historyLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, 70, 20)];
    historyLabel.text = @"历史搜索";
    historyLabel.font = [UIFont fontWithName:AppFont size:15];
    [headerView addSubview:historyLabel];
    UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(10, 60 - 1, Screen_Width - 10, 1)];
    line.image = [UIImage imageNamed:@"xuxian"];
    [headerView addSubview:line];
    self.tableView.tableHeaderView = headerView;
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, 90)];
    UIButton *clear = [UIButton buttonWithType:UIButtonTypeCustom];
    clear.frame = CGRectMake(20, 40, Screen_Width - 40, 50);
    clear.backgroundColor = UIColorFromRGB(0x03DACE);
    [clear setTitle:@"清除历史记录" forState:UIControlStateNormal];
    clear.titleLabel.font = [UIFont fontWithName:AppFont size:15];
    [clear setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    clear.userInteractionEnabled = YES;
    [clear addTarget:self action:@selector(clearHistory) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:clear];
    self.tableView.tableFooterView = footerView;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchHistoryTableViewCell" bundle:nil] forCellReuseIdentifier:SearchHistoryTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchScreenTableViewCell" bundle:nil] forCellReuseIdentifier:SearchScreenTableViewCellID];
}

#pragma mark === TableViewDelegate ===
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _searchHistoryArray.count + _conditionArray.count;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 36;
}
//Reusable
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row >= _searchHistoryArray.count || _searchHistoryArray.count == 0) {
        SearchScreenTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchScreenTableViewCellID];
        int temp = (int)indexPath.row - (int)_searchHistoryArray.count;
        [cell setScrollViewWithConditionArray:_conditionArray[temp] andTitle:_titleArray[temp]];
        cell.screen = ^(NSString *condition){
            NSLog(@"%ld, %@", indexPath.row - _searchHistoryArray.count, condition);
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        SearchHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SearchHistoryTableViewCellID];
        cell.title.text = _searchHistoryArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row < _searchHistoryArray.count) {
        _searchText.text = _searchHistoryArray[indexPath.row];
    }
}

#pragma mark === 清除历史记录 ===
- (void)clearHistory{
    [_defaults removeObjectForKey:HISTORY];
    [_searchHistoryArray removeAllObjects];
    [_tableView reloadData];
}

#pragma mark === 导航栏 ===
- (void)searching{
    if ([_searchText.text isEqualToString:@""]) {
        return;
    }
    if (_searchHistoryArray.count > 0) {
        for (int i = 0; i < _searchHistoryArray.count; i++) {
            if ([_searchText.text isEqualToString:_searchHistoryArray[i]]) {
                [_searchHistoryArray removeObjectAtIndex:i];
            }
        }
        [_searchHistoryArray insertObject:_searchText.text atIndex:0];
    }else [_searchHistoryArray addObject:_searchText.text];
    
    [_defaults setObject:_searchHistoryArray forKey:HISTORY];
    
    //网络请求... 
    SearchResultsViewController *results = [[SearchResultsViewController alloc] init];
    [self.navigationController pushViewController:results animated:YES];
}
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark === UITextFieldDelegate ===
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


@end
